// pages/logs/logs.js
import {
  carOrder,
  wechatPay
} from '../../api/settlement'
import {
  carDetail
} from '../../api/goods'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navdata:{
      loading: false,
      color: '#fff',
      background: '#f8f8f8',
      show: true,
      animated: false
    },
    info:{},
    id:{},
    orderId:'',
    give:'',
    dom_or_submiDate:{
      start: false,
      end: false,
      day:"",
      time:false,
      dateint:[]
    },
    date: {
      start: "",
      end: "",
      day:"",
      time:"",
      dateint:[]
    },
    calendarshow:false,
    tomorrow:new Date().setDate(new Date().getDate()),
    useLocation:'',
    stillLocation:''

  },
  getCarDetail(){
    carDetail({
      data:{
        id: this.data.id
      }
    })
    .then((res)=>{
      this.setData({
        info:res.data
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id:options.id
    },(()=>{
      console.log("进来了")
      this.getCarDetail()

    }))
    console.log(222)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
    this.dateinitFn()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log(this.data.date,'datedate')
    console.log(this.data.dom_or_submiDate,'domdomdom')
  },
  format(time){
    function add0(m){return m<10?'0'+m:m }
    let times  = new Date(time)
    let y = times.getFullYear();
    let m = times.getMonth()+1;
    let d = times.getDate();
    return `${y}-${add0(m)}-${add0(d)} ${this.data.dom_or_submiDate.time}:00`
  },
  //下单支付
  sendOrder(){
    let that = this;
    console.log(this.data.info.is_credential,'asdasdasd')
    if(!this.data.info.is_credential){
      wx.showModal({
        title: '提示',
        content: '您未上传证件，请上传',
        success(res) {
          // if (res.confirm) {
            wx.navigateTo({
              url: '/pages/identity/identity',
            })
            wx.hideLoading()
          // }
        }
      })
      return
    }
   if(this.data.useLocation.length==0){
     wx.showToast({
      title:'请选择取车地址',
      icon: 'none'
     })
     return
   }
    let pick_up_times = that.format(that.data.dom_or_submiDate.dateint[0]);
    let drop_off_times = that.format(that.data.dom_or_submiDate.dateint[1]);
    carOrder({
      data:{
        pick_up_time:pick_up_times,
        drop_off_time:drop_off_times,
        pick_up_location:this.data.useLocation,
        drop_off_location:this.data.stillLocation,
        car_id:this.data.info.id
      }
    })
    .then(res=>{
      let orderId = res.data.order_id
      this.setData({
        orderId:orderId
      })
      wechatPay({
        data:{
          order_id:orderId
        }
      })
      .then(r=>{
        wx.requestPayment({
          timeStamp:r.timestamp,
          nonceStr:r.nonceStr,
          package:r.package,
          signType:r.signType,
          paySign:r.paySign,
          success (res) {
            wx.reLaunch({
              url: '/pages/orderDeatil/orderDetail?id=' + that.data.orderId
            })
          },
          fail (res){
            wx.reLaunch({
              url: '/pages/orderDeatil/orderDetail?id=' + that.data.orderId
            })
          }
        })
      })
    })
  },
  //地图
  goMap(e) {
    let index = e.currentTarget.dataset.index;
    const location = {
      latitude: 39.89631551,
      longitude: 116.323459711
    };
    wx.chooseLocation({
      // location,
      success:(res=>{
        if(index == 0){
          console.log(res,'asdas')
          this.setData({
            useLocation:res.address,
            stillLocation:res.address
          })
        }else{
          this.setData({
            stillLocation:res.address
          })
        }
      })
    })
  },
  bindDateChange(e){
    console.log(e,'eeee')
    this.setData({
      date:e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

timefn(){
  this.setData({
    istime:true
  })
},
onInput(e){
  console.log(e)
  let datas = 'date.time'
  this.setData({
    [datas]: e.detail,
    istime:false
  });
},
calendarfn(e){
  console.log('1')
  let navdata = 'navdata.show'
  this.setData({
  calendarshow:true,
  [navdata]:false
  })
  console.log(this.data.dom_or_submiDate,'dom')
},
submi(){
  if(!this.data.date.end){
    wx.showToast({
      title:'必须有结束日期',
      icon:'none'
    })
    return
  }
  let navdata = 'navdata.show'
  let submiDate = this.deepClone(this.data.date);
    this.setData({
      dom_or_submiDate:submiDate,
      calendarshow:false,
      [navdata]:true
    })
    console.log(this.data.date,'date')
    console.log(this.data.dom_or_submiDate,'dom_or_submiDatedom_or_submiDate')
},
formatDate(date) {
  date = new Date(date);
  return `${date.getMonth() + 1}月${date.getDate()}日`;
},
back(){
  let navdata = 'navdata.show'
  let submiDate = this.deepClone(this.data.dom_or_submiDate);
  this.setData({
    calendarshow:false,
    [navdata]:true,
    date:submiDate
  })
  console.log(submiDate,'返回重制')
},
// getallprice(){
//   getMemberPrice({
//     data:{
//       carId:this.data.info.id,
//       days:this.data.dom_or_submiDate.day
//     }
//   })
//   .then((res)=>{
//     this.setData({
//       allprice:res.data.discountLater,
//       unallprice:parseFloat(res.data.discountLater)
//     })
//   })
// },
dataselect(e){
  let [start, end] = e.detail;
  let  startTime = new Date(start).getTime();
  let endTime = end ? new Date(end).getTime() : false;
  let dateintdata = [new Date(start).getTime(),new Date(end).getTime()]
  let cont = new Date(endTime).getDate()- new Date(startTime).getDate()
  let dates = new Date()
  let h = dates.getHours() < 10 ? `0${dates.getHours()}` : dates.getHours(); 
  let m = dates.getMinutes() < 10 ? `0${dates.getMinutes()}` : dates.getMinutes();
  let tomorrows = new Date(new Date(new Date().setDate(new Date().getDate() + 1)).toLocaleDateString()).getTime()
  let tomorrowsTime;
  if(start.getTime() == tomorrows){
    console.log('啊大撒避')
    tomorrowsTime = new Date().getHours()
    let times = "date.time"
    this.setData({
      [times]:`${h}:${m}`
    })
  }else{
    tomorrowsTime = 0
  }
  let starts = "date.start"
  let ends = "date.end"
  let days = "date.day"
  let dateints = "date.dateint"
  this.setData({
    [starts]:this.formatDate(start),
    [ends]:end ? this.formatDate(end) : false,
    [days]:new Date(endTime - startTime).getDate()-1,
    [dateints]:dateintdata,
    tomorrowtime:tomorrowsTime
  });
  console.log(this.data.date.dateint,'dateint')
},
dateinitFn(dayNum){
  let daynum = dayNum || 1;
  const dates = new Date();
  //日历默认选中天数
  let year=dates.getFullYear();
  let month=dates.getMonth();
  let today=dates.getDate()+1;
  let stat=  new Date(year,month,today).getTime();
  // ;
  let en =  new Date(year,month,today+daynum).getTime();
  let h = dates.getHours() < 10 ? `0${dates.getHours()}` : dates.getHours(); 
  let m = dates.getMinutes() < 10 ? `0${dates.getMinutes()}` : dates.getMinutes();
  let d = [stat,en]
  function GetDateStr(rt,day) {
    let dd = new Date();
    let days = day || 0;
    dd.setDate(dd.getDate()+days);//获取AddDayCount天后的日期
    var y = dd.getFullYear();
    var m = dd.getMonth()+1;//获取当前月份的日期
    var d = dd.getDate();
    console.log(daynum,'tyyyy')
    if(rt == 'y'){
      return y
    }
    if(rt == 'm'){
      return m
    }
    if (rt == 'd'){
      return d
    } 
}
  //显示文案
  // let dd = new Date()
  // dd.setDate(dd.getDate() + (1 + daynum));
  let stattxt = `${GetDateStr('m')}月${GetDateStr('d')}日`;
  let entxt = `${GetDateStr('m',daynum)}月${GetDateStr('d',daynum)}日`;
  let alldata = {
      start: stattxt,
      end: entxt,
      day: daynum,
      time:`${h}:${m}`,
      dateint:d
  }
  this.setData({
    date:this.deepClone(alldata),
    dom_or_submiDate:this.deepClone(alldata),
  });
  console.log(this.data.tomorrow,'初始化日期')
  console.log(this.data.dom_or_submiDate)
},
//深拷贝
deepClone(oldArr){
  let newArr = [];
  newArr = JSON.parse(JSON.stringify(oldArr));
  return newArr;
},
})

